import {
  selectAllRole,
  addRole,
  updateRole,
  deleteRole
} from '@/api/role'

const getDefaultState = () => {
  return {
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // user select all role
  selectAllRole({
    commit
  }, roleInfo) {
    return new Promise((resolve, reject) => {
      const {
        obj,
        page,
        pageSize
      } = roleInfo
      selectAllRole({
        obj: obj,
        page: page,
        pageSize: pageSize
      }).then(response => {
        resolve(response.data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use add role
  addRole({
    commit
  }, roleInfo) {
    return new Promise((resolve, reject) => {
      const {
        roleName
      } = roleInfo
      addRole({
        roleName: roleName
      }).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use update role
  updateRole({
    commit
  }, roleInfo) {
    return new Promise((resolve, reject) => {
      const {
        roleId,
        roleName
      } = roleInfo
      updateRole({
        roleId: roleId,
        roleName: roleName
      }).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // use delete role
  deleteRole({
    commit
  }, ids) {
    return new Promise((resolve, reject) => {
      deleteRole(ids).then(response => {
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
